package com.financing.platform.web.api;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.financing.platform.common.CommonConstantUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.AccessInfoDTO;
import com.financing.platform.dto.GroupDTO;
import com.financing.platform.dto.UserGroupDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.dto.ZtreeDTO;
import com.financing.platform.service.IAccessControlService;
import com.financing.platform.service.IFaUserService;
import com.financing.platform.service.IFpFundInfoService;
import com.financing.platform.service.IGroupService;
import com.financing.platform.service.IManagerOrderService;
import com.financing.platform.service.IProjectService;
import com.financing.platform.service.IUserGroupService;
import com.financing.platform.service.IUserInfoService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.MemcacheCacheHelper;
import com.financing.platform.util.StringUtil;

/**
 * 
* @ClassName: UserInfoAction 
* @Description: 用户信息 
* @author chenming 
* @date 2014年7月27日 下午4:58:38 
*
 */
@Controller("userInfoActionAPI")
@RequestMapping("/api")
@Scope("prototype")
public class UserInfoAction extends BaseAction {

	@Autowired
	private IUserInfoService userInfoServiceImpl;
	
	@Autowired
	private IAccessControlService accessControlServiceImpl;
	
	@Autowired
	private IGroupService groupServiceImpl;
	
	@Autowired
	private IUserGroupService userGroupServiceImpl;
	
	@Value("#{settings['allow_ip']}")
	private String allow_ip;
	
	@Value("#{settings['quDaoLeaderUserId']}")
	private String leaderId;
	
	@Autowired
	private IManagerOrderService managerOrderServiceImpl;
	
	@Autowired
	private IFaUserService faUserServiceImpl;
	
	@Autowired
	private IProjectService projectService;
	
	@Autowired
	private IFpFundInfoService fpFundInfoService;
	
	/**
	 * 
	* @Title: login 
	* @Description: 用户登录
	* @param   request
	* @param   response
	* @param   accessInfoDto
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/login.shtml")
	@ResponseBody
	public ResultMap login(HttpServletRequest request,
			HttpServletResponse response,UserInfoDTO userInfoDTO) {
		try{
			HttpSession session = request.getSession();
			this.log.info("Begin login!");
			
			if(!request.getAttribute("ip").equals(allow_ip)){
				//TODO 手机动态验证码校验
			}
			log.info("verifyCode result is "+checkVerifyCode(request));
				
				boolean loginStatus = false;
				if(null != userInfoDTO && null != userInfoDTO.getUserNickname() && null != userInfoDTO.getPassword()){
					loginStatus = userInfoServiceImpl.userLogin(userInfoDTO);
				}
				
				if(loginStatus){
					userInfoDTO = userInfoServiceImpl.queryUserInfo(userInfoDTO);
					
					MemcacheCacheHelper.mcc.set(userInfoDTO.getUserId()+userInfoDTO.getUserNickname()+request.getServerName(), session.getId());
					
					resultMap.setAttribute("userNickName", userInfoDTO.getUserNickname());
					resultMap.setAttribute("userName",userInfoDTO.getUsername());
					resultMap.setAttribute("id",userInfoDTO.getUserId());
					
					UserGroupDTO userGroupDTO = new UserGroupDTO();
					userGroupDTO.setUserId(userInfoDTO.getUserId());
					
					//查询用户所在组
					List<UserGroupDTO> listUserGroup = userGroupServiceImpl.queryUserGroup(userGroupDTO);
					
					resultMap.setAttribute("groups",listUserGroup);
					Map<String,Object> accessInfoMap = new HashMap<String,Object>();
					
					List<AccessInfoDTO> accessList = new ArrayList<AccessInfoDTO>();
					for(UserGroupDTO userGroupDTOTemp : listUserGroup){
						GroupDTO group = new GroupDTO();
						group.setGroupId(userGroupDTOTemp.getGroupId());
						
						//查询用户组权限信息
						List<AccessInfoDTO> accessInfoDTOList = accessControlServiceImpl.queryAccessForGroup(group);
						
						for(AccessInfoDTO accessInfoDto : accessInfoDTOList){
							accessInfoMap.put(accessInfoDto.getActionName(), null);
							accessList.add(accessInfoDto);
						}
					}
					userInfoDTO.setAccessList(accessList);
					session.setAttribute(DTOdateSet.user, userInfoDTO);
					
					if("admin".equals(userInfoDTO.getUserNickname())){
						resultMap.setAttribute("access", "all");
					}else{
						resultMap.setAttribute("access", accessInfoMap.keySet());
					}
					
					resultMap.setStatus(STATUS.SUCCESS);
					resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
					this.log.info("End login!");
					return resultMap;
				}
			}catch(Exception e){
				log.error("login error !",e);
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
		
		resultMap.setStatus(STATUS.FAILE);
		resultMap.setStatusCode(ResultCode.RESULT_CODE_LOGIN_ERROR);
			
		return resultMap;
	}
	
	/**
	 * 
	* @Title: login 
	* @Description: 用户登录
	* @param   request
	* @param   response
	* @param   accessInfoDto
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/accessList.shtml")
	@ResponseBody
	public ResultMap accessList(HttpServletRequest request,
			HttpServletResponse response) {
		try{
			HttpSession session = request.getSession();
			UserInfoDTO userInfoDTO = (UserInfoDTO) session.getAttribute(DTOdateSet.user);
			UserGroupDTO userGroupDTO = new UserGroupDTO();
			userGroupDTO.setUserId(userInfoDTO.getUserId());
					
			//查询用户所在组
			List<UserGroupDTO> listUserGroup = userGroupServiceImpl.queryUserGroup(userGroupDTO);
					
			resultMap.setAttribute("groups",listUserGroup);
			Map<String,Object> accessInfoMap = new HashMap<String,Object>();
					
			for(UserGroupDTO userGroupDTOTemp : listUserGroup){
						
				GroupDTO group = new GroupDTO();
				group.setGroupId(userGroupDTOTemp.getGroupId());
						
				//查询用户组权限信息
				List<AccessInfoDTO> accessInfoDTOList = accessControlServiceImpl.queryAccessForGroup(group);
				for(AccessInfoDTO accessInfoDto : accessInfoDTOList){
					accessInfoMap.put(accessInfoDto.getActionName(), null);
				}
			}
					
			if("admin".equals(userInfoDTO.getUserNickname())){
				resultMap.setAttribute("access", "all");
			}else{
				resultMap.setAttribute("access", accessInfoMap.keySet());
			}
					
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			return resultMap;
			}catch(Exception e){
				log.error("login error !",e);
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
		
		return resultMap;
	}

	/**
	 * 
	* @Title: checkCode 
	* @Description: 校验动态验证码
	* @param @param request
	* @param @return    
	* @return boolean   
	* @throws
	 */
	private boolean checkVerifyCode(HttpServletRequest request){
		String code = request.getParameter("code");
		String seesionCode = (String) request.getSession().getAttribute("code");
		if(code == null || seesionCode == null){
			return false;
		}
		return seesionCode.equals(code);
	}
	
	
	/**
	 * 
	* @Title: queryAllUser 
	* @Description:  查询所有用户
	* @param @param request
	* @param @param response
	* @param @param userInfoDTO
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/queryAllUser.shtml")
	@ResponseBody
	public ResultMap queryAllUser(HttpServletRequest request,
			HttpServletResponse response,UserInfoDTO userInfoDTO){
		
		try{
			
			userInfoDTO.setStatus("0");
			
			List<UserInfoDTO> list = userInfoServiceImpl.queryAllUserInfo(userInfoDTO);
			
			resultMap.setAttribute("list", list);
			resultMap.setAttribute("useInfoDTO", userInfoDTO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryAllUser error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
		
	}
	
	/**
	 * 
	* @Title: user 
	* @Description: 查询单用户信息
	* @param   request
	* @param   response
	* @param   userInfoDTO
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/queryUserInfo.shtml")
	@ResponseBody
	public ResultMap user(HttpServletRequest request,
			HttpServletResponse response,UserInfoDTO userInfoDTO){
		
		try{
			UserInfoDTO userInfo = userInfoServiceImpl.queryUserInfo(userInfoDTO);
			if( userInfo != null && StringUtils.isNotBlank(userInfo.getParentUserId())){
				UserInfoDTO  paremtUser =  new UserInfoDTO();
				paremtUser.setUserId(userInfo.getParentUserId());
				paremtUser = userInfoServiceImpl.queryUserInfo(paremtUser);

				if(paremtUser != null){
					userInfo.setParentUserName(paremtUser.getUserNickname());
				}
			}
			if( userInfo != null && StringUtils.isNotBlank(userInfo.getDeptHead())){
				UserInfoDTO  paremtUser =  new UserInfoDTO();
				paremtUser.setUserId(userInfo.getDeptHead());
				paremtUser = userInfoServiceImpl.queryUserInfo(paremtUser);

				if(paremtUser != null){
					userInfo.setDeptHeadName(paremtUser.getUserNickname());
				}
			}
			if( userInfo != null && StringUtils.isNotBlank(userInfo.getPublicDeptHead())){
				UserInfoDTO  paremtUser =  new UserInfoDTO();
				paremtUser.setUserId(userInfo.getPublicDeptHead());
				paremtUser = userInfoServiceImpl.queryUserInfo(paremtUser);

				if(paremtUser != null){
					userInfo.setPublicDeptHeadName(paremtUser.getUserNickname());
				}
			}
			
			List<GroupDTO> allGroups = groupServiceImpl.queryAllGroup(new GroupDTO());
			
			UserGroupDTO userGroupDto = new UserGroupDTO();
			userGroupDto.setUserId(userInfoDTO.getUserId());
			List<UserGroupDTO> selectGroups = userGroupServiceImpl.queryUserGroup(userGroupDto);
			
			resultMap.setAttribute("userInfo", userInfo);
			resultMap.setAttribute("allGroups", allGroups);
			resultMap.setAttribute("selectGroups", selectGroups);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryAllUser error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		
		return resultMap;
	}
	
	/**
	 * 
	* @Title: updateUserInfo 
	* @Description:  更新用户信息
	* @param   request
	* @param   response
	* @param   userInfoDTO
	* @return ModelAndView   
	* @throws
	 */
		@RequestMapping("/updateUserInfo.shtml")
	@ResponseBody
	public ResultMap updateUserInfo(HttpServletRequest request,
			HttpServletResponse response,UserInfoDTO userInfoDTO){
		
		try{
			//getDeptHead is  null  update
			if(StringUtils.isBlank(userInfoDTO.getDeptHead()) || "-1".equals(userInfoDTO.getDeptHead())){
				userInfoDTO.setDeptHead(" ");
			}
			//getPublicDeptHead is  null  update
			if(StringUtils.isBlank(userInfoDTO.getPublicDeptHead()) || "-1".equals(userInfoDTO.getPublicDeptHead())){
				userInfoDTO.setPublicDeptHead(" ");
			}

			UserInfoDTO userInfo = userInfoServiceImpl.updateUserInfo(userInfoDTO);

			//getParentUserId is not null  update
			if(StringUtils.isNotBlank(userInfoDTO.getParentUserId()) && !"-1".equals(userInfoDTO.getParentUserId())){
				UserInfoDTO  paremtUser =  new UserInfoDTO();
				paremtUser.setUserId(userInfoDTO.getParentUserId());
				paremtUser = userInfoServiceImpl.queryUserInfo(paremtUser);

				if(paremtUser != null){
					userInfoDTO.setLayerPath(paremtUser.getLayerPath()+","+userInfoDTO.getUserId());
					userInfoServiceImpl.updateUserInfo(userInfoDTO);
				}
				updateChildLayerPath(userInfoDTO.getUserId(),userInfoDTO,1);
			}else{
				userInfoDTO.setParentUserId(" ");
				userInfoDTO.setLayerPath(userInfoDTO.getUserId());
				userInfoServiceImpl.updateUserInfo(userInfoDTO);
				updateChildLayerPath(userInfoDTO.getUserId(),userInfoDTO,1);
			}

			
			String[] groupsId = request.getParameter("groupId").split("[,]");
			
			UserGroupDTO userGroupDto = new UserGroupDTO();
			userGroupDto.setUserId(userInfoDTO.getUserId());
			userGroupServiceImpl.deleteUserGroup(userGroupDto);
			
			DTOdateSet.setCreateInfo(userGroupDto, request.getSession());
			DTOdateSet.setUpdateInfo(userGroupDto, request.getSession());
			
			if(groupsId != null){
				userGroupServiceImpl.saveUserGroup(groupsId,userGroupDto);
			}
			
			List<GroupDTO> allGroups = groupServiceImpl.queryAllGroup(new GroupDTO());
			List<UserGroupDTO> selectGroups = userGroupServiceImpl.queryUserGroup(userGroupDto);
			// 离职人员的订单派发给领导
			if(!"".equals(userInfoDTO.getStatus().trim()) && "2".equals(userInfoDTO.getStatus())){
				Map<String, Object> toLeader = new HashMap<String, Object>();
				toLeader.put("updateDate", new Date(System.currentTimeMillis()));
				toLeader.put("updateBy", ((UserInfoDTO) request.getSession().getAttribute("USER")).getUsername());
				toLeader.put("fromUserId", userInfoDTO.getUserId());
				toLeader.put("toUserId", leaderId);
				managerOrderServiceImpl.order2Leader(toLeader);
			}
			resultMap.setAttribute("userInfo", userInfo);
			resultMap.setAttribute("allGroups", allGroups);
			resultMap.setAttribute("selectGroups", selectGroups);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("updateUserInfo error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	/**
	 * 
	* @Title: logout 
	* @Description: 登出
	* @param   request
	* @param   response
	* @return ResultMap   
	* @throws
	 */
	@RequestMapping("/logout.shtml")
	@ResponseBody
	public ResultMap logout(HttpServletRequest request,
			HttpServletResponse response){
		
		try{
	
			request.getSession().invalidate();
			
			Cookie[] cookies = request.getCookies();  
			for(int i=0;i<cookies.length;i++){  
				Cookie cookie = new Cookie(cookies[i].getName(), null);  
				cookie.setMaxAge(0);
				response.addCookie(cookie);
			}
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("logout error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return  resultMap;
	}
	
	@RequestMapping("/addUser.shtml")
	@ResponseBody
	public ResultMap addUser(HttpServletRequest request,HttpServletResponse response,UserInfoDTO userInfo){
		try{
			DTOdateSet.setCreateInfo(userInfo, request.getSession());
			DTOdateSet.setUpdateInfo(userInfo, request.getSession());
			//getDeptHead is  null  update
			if(StringUtils.isBlank(userInfo.getDeptHead()) || "-1".equals(userInfo.getDeptHead())){
				userInfo.setDeptHead(" ");
			}

			userInfo = userInfoServiceImpl.addUserInfo(userInfo);
			if(userInfo == null){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}

			//getParentUserId is not null  update
			if(StringUtils.isNotBlank(userInfo.getParentUserId()) &&!"-1".equals(userInfo.getParentUserId())){
				UserInfoDTO  paremtUser =  new UserInfoDTO();
				paremtUser.setUserId(userInfo.getParentUserId());
				paremtUser = userInfoServiceImpl.queryUserInfo(paremtUser);

				if(paremtUser != null){
					userInfo.setPassword(null);
					userInfo.setLayerPath(paremtUser.getLayerPath()+","+userInfo.getUserId());
					userInfoServiceImpl.updateUserInfo(userInfo);
				}
			}else{
				userInfo.setPassword(null);
				userInfo.setParentUserId(" ");
				userInfo.setLayerPath(userInfo.getUserId());
				userInfoServiceImpl.updateUserInfo(userInfo);
			}

			String[] groupsId = request.getParameter("groupId").split("[,]");
			
			UserGroupDTO userGroupDto = new UserGroupDTO();
			userGroupDto.setUserId(userInfo.getUserId());
			userGroupServiceImpl.deleteUserGroup(userGroupDto);
			
			DTOdateSet.setCreateInfo(userGroupDto, request.getSession());
			DTOdateSet.setUpdateInfo(userGroupDto, request.getSession());
			
			if(groupsId != null){
				userGroupServiceImpl.saveUserGroup(groupsId,userGroupDto);
			}
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("add user error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	

	@RequestMapping("/viewVerifyCode.shtml")
	public void viewVerifyCode(HttpServletRequest request, HttpServletResponse response){
		HttpSession session = request.getSession();
		try {
			String code = StringUtil.createRandomChineseCharactersImage(response.getOutputStream());
			log.info("verifyCode is :"+code);
			session.setAttribute("code",code);
		} catch (Exception e) {
			log.error("create random chinese characters image error!",e);
		}finally{
			try {
				response.getOutputStream().flush();
			} catch (IOException e) {
				log.error("resopnse out image error",e);
			}
		}
		return ;
	} 
	
	@RequestMapping("/queryLoginStatus.shtml")
	@ResponseBody
	public ResultMap queryLoginStatus(HttpServletRequest request){
		try{
			UserInfoDTO userInfo = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			if(userInfo != null && userInfo.getUsername() != null){
				resultMap.setAttribute("loginStatus", true);
			}else{
				resultMap.setAttribute("loginStatus", false);
			}
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryLoginStatus error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	/**
	 *
	 * @Title: listTree
	 * @Description:  树形层级
	 * @param @param request
	 * @param @param response
	 * @param @param userInfoDTO
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping("/listTree.shtml")
	@ResponseBody
	public ResultMap listTree(HttpServletRequest request,
								  HttpServletResponse response,UserInfoDTO userInfoDTO){

		try{

			userInfoDTO.setStatus("0");
			List<UserInfoDTO> list = userInfoServiceImpl.queryAllUserInfo(userInfoDTO);
			List<ZtreeDTO> ztreeDTOList =  new ArrayList<ZtreeDTO>();
			ZtreeDTO ztdc = new ZtreeDTO();
			ztdc.setId("-1");
			ztdc.setpId("");
			ztdc.setName("顶层机构");
			ztreeDTOList.add(ztdc);
			for (UserInfoDTO z:list){
				ZtreeDTO zt = new ZtreeDTO();
				zt.setId(z.getUserId());
				zt.setpId(z.getParentUserId());
				zt.setName(z.getUserNickname());
				zt.setType(z.getUserType());
				ztreeDTOList.add(zt);
			}

			resultMap.setAttribute("list", ztreeDTOList);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("listTree error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;

	}
	private void updateChildLayerPath(String parentUserId,UserInfoDTO parentUserInfo,int i){
		if(i>10){
			return ;
		}
		UserInfoDTO userInfoDTO = new UserInfoDTO();
		userInfoDTO.setParentUserId(parentUserId);
		List<UserInfoDTO> list = userInfoServiceImpl.queryAllUserInfo(userInfoDTO);
		for(UserInfoDTO bean : list){
			bean.setLayerPath(parentUserInfo.getLayerPath()+","+bean.getUserId());
			userInfoServiceImpl.updateUserInfo(bean);
			updateChildLayerPath(bean.getUserId(),bean,++i);
		}
	}

	@RequestMapping("/queryLoginInfo.shtml")
	@ResponseBody
	public ResultMap queryLoginInfo(HttpServletRequest request){
		try{
			UserInfoDTO userInfo = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);

			UserInfoDTO  loginInfo =  new UserInfoDTO();
			loginInfo.setUserId(userInfo.getUserId());
			loginInfo = userInfoServiceImpl.queryUserInfo(loginInfo);
			if(userInfo != null && userInfo.getUsername() != null){
				resultMap.setAttribute("loginInfo",loginInfo);
			}
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryLoginStatus error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}

	@RequestMapping("/updateLoginInfo.shtml")
	@ResponseBody
	public ResultMap updateLoginInfo(HttpServletRequest request,String password,String telePhone,String email){
		try{

			UserInfoDTO userInfo = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			UserInfoDTO  loginInfo =  new UserInfoDTO();
			loginInfo.setPassword(password);
			loginInfo.setUserId(userInfo.getUserId());
			if(StringUtils.isNotBlank(telePhone)) {
				loginInfo.setTelePhone(telePhone);
			}
			if(StringUtils.isNotBlank(email)) {
				loginInfo.setEmail(email);
			}

			loginInfo.setUserNickname(userInfo.getUserNickname());
			userInfoServiceImpl.updateUserInfo(loginInfo);

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryLoginStatus error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	/***
	 * 名单回访详情
	 * @param request
	 * @param response
	 * @param orderVo
	 * @param page
	 */
	@RequestMapping("/queryVistDetail.shtml")
	@ResponseBody
	public ResultMap queryVistDetail(HttpServletRequest request) {
		
		ResultMap result = new ResultMap();
		log.info("in queryVistDetail begin!");
        try{
        	//当前登录用户id
        	UserInfoDTO userinfo = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
        	String currentUserId=userinfo.getUserId();
        	
        	//当前登录用户的用户访问详情
        	Map<String, Object> map=new HashMap<String,Object>();
        	map.put("systemUserId",currentUserId);
        	map.put("sysUserId","self");//查询自己
        	List<Map<String, Object>> current = userInfoServiceImpl.queryVistDetail(map);
        	result.setAttribute("self",current.size()>0?current.get(0):null);

        	//团队下所有人访问流水
        	map.put("sysUserId", "");
        	//获取当前登录是否admin
        	getSystemIsCurrent(request, map);
        	//获取当前用户下所有用户子账户
        	getSystemIds(map);
        	String sysId = (String) map.get("systemUserId");
        	//移除自己
        	sysId=sysId.replace(currentUserId, "").replace(",,", ",");
        	if(!StringUtil.isNullOrEmptyNStr(sysId)){
        		map.put("systemUserId", sysId);
        		List<Map<String, Object>> subAccount = userInfoServiceImpl.queryVistDetail(map);
        		result.setAttribute("subAccount",subAccount);
        	}else{
        		result.setAttribute("subAccount",Collections.EMPTY_LIST);
        	}
        	
            log.info("in queryVistDetail End!");
            result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
        }catch(Exception e){
            log.error("queryVistDetail error !",e);
            result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
        }

        return result;
    }
	/***
	 * 关注客户--内部理财师
	 */
	@RequestMapping("/customerFocus.shtml")
	@ResponseBody
	public ResultMap customerFocus(HttpServletRequest request) {
		
		ResultMap result = new ResultMap();
		log.info("in customerFocus begin!");
        try{
        	//当前登录用户id
        	UserInfoDTO userinfo = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
        	String currentUserId=userinfo.getUserId();
        	
        	//查询用户下所有理财师的手机号
        	Map<String, Object> map=new HashMap<String,Object>();
        	map.put("systemUserId",currentUserId);
        	Map<String,String> man = userInfoServiceImpl.queryUserPhoneByManagerLCS(map);
        	
        	Set<String> hm=new HashSet<String>();
        	//手机号
        	for (Entry<String, String> phone : man.entrySet()) {
				hm.add(phone.getKey());
			}
        	List<JSONObject> res=new ArrayList<JSONObject>();
        	
        	String userProjectUrl=mongoDBLink+"wapData/userProject";
        	String userProject = urlconnection(userProjectUrl);
        	JSONObject json = JSONObject.fromObject(userProject);
			JSONObject attribute = json.getJSONObject("attributes");
			JSONArray list = attribute.getJSONArray("list");
			for (int i = 0; i < list.size(); i++) {
				JSONObject object = (JSONObject) list.get(i);
				Object userMobile=object.get("userMobile");
				if(userMobile==null){
					continue;
				}
				//只需要查询10条记录
				if(hm.contains(String.valueOf(userMobile))){
					object.put("userName", man.get(userMobile));
					Object code = object.get("param");
					if(code==null){
						continue;
					}
					String codeStr = String.valueOf(code);
					Map<String, Object> productMap = new HashMap<String,Object>();
					if(codeStr.matches("\\d+")){//基金
						productMap = fpFundInfoService.queryFundInfoNameById(codeStr);
					}else{//非基金
						productMap = projectService.queryPnameByCode(codeStr);
					}
					if(productMap == null){
						continue;
					}
					object.put("productName", productMap.containsKey("name")?productMap.get("name"):null);
					object.put("productType", productMap.containsKey("type")?productMap.get("type"):null);

					getCustomerFocusBehavior(object);

					res.add(object);
					if(res.size()>=10){
						break;
					}
				}
			}
			
			result.setAttribute("list",res);
            log.info("in customerFocus End!");
            result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
        }catch(Exception e){
            log.error("customerFocus error !",e);
            result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
        }

        return result;
    }
    private  void  getCustomerFocusBehavior(JSONObject object){
		if(!object.containsKey("type")){
			object.put("behavior","");
			return;
		}
		String type = CommonConstantUtil.customerFocusBehaviorMap.get(object.get("type"));
		if(StringUtils.isBlank(type)){
			object.put("behavior",object.get("type"));
			return;
		}
		String productType = object.get("productType")==null?"":CommonConstantUtil.productTypeMap.get(object.get("productType"));
		object.put("behavior", MessageFormat.format(type,productType));
	}

}
